﻿using Bricks.Injecting;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;

namespace Bricks.Unity.Injecting
{

    /// <summary>
    /// 
    /// </summary>
    public class UnityContainerFacade : ContainerFacadeBase<IUnityContainer>, IUnityContainerFacade
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="unityContainer"></param>
        public UnityContainerFacade(IUnityContainer unityContainer) :
            base(unityContainer)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public override object Resolve(Type serviceType, string key)
        {
            return Execute<object>(unityContainer => unityContainer.Resolve(serviceType, key));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public override IEnumerable<object> ResolveAll(Type serviceType)
        {
            return Execute<IEnumerable<object>>(unityContainer => unityContainer.ResolveAll(serviceType));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public override TService Resolve<TService>(string key)
        {
            return Execute<TService>(unityContainer => unityContainer.Resolve<TService>(key));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <returns></returns>
        public override IEnumerable<TService> ResolveAll<TService>()
        {
            return Execute<IEnumerable<TService>>(unityContainer => unityContainer.ResolveAll<TService>());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="service"></param>
        public override void Release(object service)
        {
            Execute(unityContainer => unityContainer.Teardown(service));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override IContainerFacade CreateChild()
        {
            return Execute<IContainerFacade>(
                unityContainer =>
                {
                    return new UnityContainerFacade(unityContainer.CreateChildContainer());
                });
        }
    }
}
